/**
 * @Author: jinye
 * @Date:   2016-02-24 15:19:59
 */

'use strict';
var fs      = require('fs');
var path    = require('path');
var gulp    = require('gulp');
var gutil   = require('gulp-util');
var argv    = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var rimraf  = require('rimraf');
var proxy   = require('http-proxy-middleware');

var ROOT_PATH = process.cwd() + '/src';
var DIST_PATH = process.cwd() + '/dist';

var DEBUG = !!argv.debug;
var TEST  = !!argv.test;

var webpackConfig = require('./webpack.make')({debug: DEBUG});

function readHTMLFile () {
    var files = fs.readdirSync(DIST_PATH) || [];
    var temp  = []
    files.map(function (f) {
        if ( /html/.test(f) ) {
            temp.push(path.join(DIST_PATH, f))
        }
    })
    return temp;
}

/*
 |--------------------------------------------------------------------------
 | HTTP Server 服务器
 |--------------------------------------------------------------------------
 */
gulp.task('browser-sync', function () {

    var browserSync = require('browser-sync').create();
    var compiler    = webpack(webpackConfig), bundleStart = null;

    var webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
        // IMPORTANT: dev middleware can't access config, so we should
        // provide publicPath by ourselves
        publicPath: webpackConfig.output.publicPath,
        // pretty colored output
        stats     : {colors: true, chunks: false}
        // for other settings see
        // http://webpack.github.io/docs/webpack-dev-middleware.html
    })

    var webpackHotMiddleware = require('webpack-hot-middleware')(compiler);

    var proxyMiddleware = proxy('/ctg-sysmgr-permission-demo', {
        target  : "http://134.132.93.202:8098",
        logLevel: 'debug'
    })

    compiler.plugin('compile', function () {
        console.log('Bundling...');
        bundleStart = Date.now();
    });

    // We also give notice when it is done compiling, including the
    // time it took. Nice to have
    compiler.plugin('done', function () {
        console.log('Bundled in ' + (Date.now() - bundleStart) + 'ms!');
    });

// force page reload when html-webpack-plugin template changes
    compiler.plugin('compilation', function (compilation) {
        compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
            webpackHotMiddleware.publish({action: 'reload'})
            cb()
        })
    })

    browserSync.init({
        server: {
            baseDir   : './src',
            middleware: [ webpackDevMiddleware, webpackHotMiddleware, proxyMiddleware ],
            files     : [
                ROOT_PATH + '*.html'
            ]
        },
        port  : "8088",
        open  : false
    })
})

gulp.task('js-hint', function () {
    var jshint  = require('gulp-jshint');
    var stylish = require('jshint-stylish');
    return gulp.src([
        ROOT_PATH + '/*.js', ROOT_PATH + '/views/**/*.js'
    ]).pipe(jshint()).pipe(jshint.reporter(stylish));
});

gulp.task('clean', function (cb) {
    rimraf(DIST_PATH, cb)
})

// webpack 打包任务
gulp.task("pack", [ 'clean' ], function (callback) {
    webpack(webpackConfig, function (err, stats) {
        if ( err ) throw new gutil.PluginError("webpack", err);
        gutil.log('[webpack]', stats.toString({colors: true, profile: true, chunks: false}));
        callback();
    });
});

gulp.task('test', function (done) {
    var Server = require('karma').Server;
    Server.start({
        configFile: __dirname + '/karma.config.js'
    }, function () {
        done()
    })
});


gulp.task('production', [ 'copy:js', 'copy:css', 'copy:font', 'path' ], function () {
    var browserSync = require('browser-sync').create();
    browserSync.init({
        server : {
            baseDir: './dist'
        },
        browser: []
    })
});

gulp.task('copy:css', function () {
    return gulp.src(ROOT_PATH + '/assets/css/**/*').pipe(gulp.dest(DIST_PATH + '/css'))
});

gulp.task('copy:font', function () {
    return gulp.src(ROOT_PATH + '/assets/fonts/**/*').pipe(gulp.dest(DIST_PATH + '/fonts'))
});

gulp.task('copy:js', function () {
    return gulp.src(ROOT_PATH + '/assets/libs/**/*').pipe(gulp.dest(DIST_PATH + '/libs'))
});

gulp.task('path', function () {
    var replace   = require('gulp-replace');
    var htmlFiles = readHTMLFile();
    return gulp.src(htmlFiles)
               .pipe(replace(/assets\//g, ''))
               .pipe(replace(/\.\.\//g, ''))
               .pipe(gulp.dest(DIST_PATH));
});

gulp.task("default", function () {
    var runSequence = require('run-sequence');
    if ( DEBUG ) return runSequence('browser-sync');
    if ( TEST ) return runSequence('test');
    runSequence('pack', 'production')
});